<?php
namespace app\index\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
class Feedback  extends Base{
    const templatePath='data/feedbackTemp/';//模板文件所在路径
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->CatModel=new \app\index\model\FeedbackCatModel();
        $this->Model=new \app\index\model\FeedbackModel();
        $this->FieldModel=new \app\index\model\FeedbackFieldModel();
        $this->validate=new \app\index\validate\FeedbackValidate();
        $this->mobile=new \app\common\MobileVerify\MobileVerify();
        
        $catid=Request::param("catid",0,"intval");
        $this->cat=$this->CatModel->find($catid);
        if(!$this->cat){
            $this->error("当前留言反馈分类不存在！");
        }
        if(!$this->cat['status']){
            $this->error("当前留言分类已经被禁用！");
        }        
        View::assign("pagetitle",$this->cat['name']);
        View::assign("cat",$this->cat);
        View::assign("catTemplatePath",base_path().self::templatePath.$this->cat['catid'].".html");
    }    
    public function index(){
        $feedbackTemp=View::fetch(base_path().self::templatePath.$this->cat['catid'].".html");
        View::assign("feedbackTemp",$feedbackTemp);
        return View::fetch();
    }
    public function add(){
        $data=$this->request->param();
        //验证
        $this->dataCheck($data);
        //数据处理
        $data=$this->dataCreate($data);
        $this->Model->save($data);
        //是否要发送邮件
        if($this->cat["request_email"]){
            $this->sendMail($data);
        }
        //清空短信验证码放到这里的原因是，如果短信验证成功，但是其它字段验证不能过，又需要重新获取验证码，所以在保存信息以后再清空验证码，增加用户体验，节约短信资源
        if($this->cat["mobile_verify_code"]){
            $this->mobile->clear();//清空验证码
        }
        $this->success($result);
    }    
    //发送验证码
    public function sendMobileCode(){
        $data=Request::param();
        //rule里同一个字段多个验证规则，要用|隔开
        $validate = \think\facade\Validate::rule(['mobile'=>'require|mobile'])->message([
            "mobile.require"=>"请填写手机号码",
            "mobile.mobile"=>"手机号码格式错误",
        ]);        
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }        
        $result=$this->mobile->send_code($data['mobile']);
        if($result){
            $this->success("短信发送成功");
        }else{
            $this->error($this->mobile->error);
        }
    }  
    //发送邮件
    private function sendMail($r){   
        //
        if($r['member_id']){
            $truename=Db::name("member")->where("member_id",$r['member_id'])->value("truename");
        }
        $formtemp=$this->cat["formtemp"];
        $formtemp=explode("\r\n",$formtemp); 
        $content="";            
        foreach($formtemp as $key=>$v){            
            $val=explode("<!--field-->",$v); 
            //判断是否为录入字段
            if(!strstr($this->cat["is_enter"],",".$val[1].",")){
                continue;
            }
            $newdata[$key]["name"]=$val[0];
            $newdata[$key]["field"]=$val[1];
            $newdata[$key]["value"]=$r[$val[1]];
            //判断字段类型，时间字段和多值字段要转换
            $field=Db::name("feedback_field")->where(array("field"=>$val[1]))->find();            
            if($field['formtype']=="date"){
                $newdata[$key]["value"]=$newdata[$key]["value"]?date("Y-m-d H:i:s",$newdata[$key]["value"]):"";
            }
            if($field['formtype']=="morevalue"){
                $morevalue_str='<table width="100%" cellspacing="1" cellpadding="0" border="0" bgcolor="#939393" style="font-size:16px;margin:-1px">';
                //列名
                $morevalueField=str2arr($field['defaultval'],"{{RsSplit}}","{{FieldSplit}}");
                $morevalue_str.="<tr>";
                foreach($morevalueField as $v2){     
                    $morevalue_str.='<td class="center" bgcolor="#D7D6D6" width="'.$v2[3].'%">'.$v2[0].'</td>';
                }    
                $morevalue_str.="</tr>";
                //内容
                $morevalue=str2arr($newdata[$key]["value"],"{{RsSplit}}","{{FieldSplit}}");
                foreach($morevalue as $v2){
                    $morevalue_str.="<tr>";
                    foreach($morevalueField as $k3=>$v3){
                        $morevalue_str.='<td class="center" bgcolor="#FFFFFF">'.$v2[$k3].'</td>';
                    }
                    $morevalue_str.="</tr>";
                }
                $morevalue_str.="</table>";
                $newdata[$key]["value"]=$morevalue_str;
            }
            $content.='<tr>
            <td bgcolor="#D7D6D6">'.$newdata[$key]["name"].'</td>
            <td bgcolor="#FFFFFF">'.$newdata[$key]["value"].'</td>
          </tr>';            
            //
        }        
        $mail_temp='<h1>您的网站有人留言啦！</h1><p>留言网址：'. 'http://'.$_SERVER['HTTP_REFERER'].'</p><table width="90%" cellspacing="1" cellpadding="0" border="0" bgcolor="#939393" style="font-size:20px;">
            <tbody>
              <tr>
                <td width="18%" bgcolor="#D7D6D6">分类</td>
                <td width="82%" bgcolor="#FFFFFF" font="16px">'.$this->cat["name"].'</td>
              </tr>
              <tr>
                <td bgcolor="#D7D6D6">提交时间</td>
                <td bgcolor="#FFFFFF">'.date("Y-m-d H:i:s",$r['addtime']).'</td>
              </tr>
              <tr>
                <td bgcolor="#D7D6D6">IP地址</td>
                <td bgcolor="#FFFFFF">'.$r['ip'].'</td>
              </tr>
              <tr>
                <td bgcolor="#D7D6D6">会员</td>
                <td bgcolor="#FFFFFF">'.($truename?$truename:'游客').'</td>
              </tr>'.$content.'
            </tbody>
          </table>
          ';
        $phpMailer=new \app\common\PhpMail\PhpMail();
        $email_arr=explode(",",$this->cat["request_email"]);
        foreach($email_arr as $email){
            $phpMailer->sendMail($email,"最新留言-".$this->cat["name"],$mail_temp);
        }        
    }       
    //验证数据
    private function dataCheck($data){
        //录入项
        $is_enter=$this->cat["is_enter"];        
        $is_enter_arr=explode(",",trim($is_enter,","));
        $where=[];
        $where[]=["field","in",$is_enter_arr];
        $fieldarr=$this->FieldModel->where($where)->select()->toArray();     
        foreach($fieldarr as $v){
            //必填项(不能为空验证)
            if(strstr($this->cat["must_enter"],",".$v['field'].",")){   
                //echo $v['field'];
                //判断是不是checkbox,如果是执行函数验证
                if($v['formtype']=="checkbox"){
                    $this->validate->message[$v['field'].".require"]=$v['name']."必须勾选!";
                    $this->validate->rule[$v['field']][]="require";
                }
                else if($v['formtype']=="morevalue"){
                    //多值字段，这里就不做验证了
                }                
                else{
                    $this->validate->message[$v['field'].".require"]="Please fill in ".$v['name']."!";
                    $this->validate->rule[$v['field']][]="require";
                }
            }
            //正则验证
            if($v['pattern']){
                $this->validate->message[$v['field'].".regex"]=$v['errortips']?$v['errortips']:$v['name']."验证不通过!";
                $this->validate->regex[$v['field']."_regex"]=$v['pattern'];
                $this->validate->rule[$v['field']]["regex"]=$v['field']."_regex";
            }
            //值维一验证
            if($v['isunique']){
                $this->validate->message[$v['field'].".unique"]=$v['name']."对应的记录已存在!";
                $this->validate->rule[$v['field']]["unique"]="feedback";
            }
        }
        //
        if(!$this->validate->check($data)){
            $this->error($this->validate->getError());
        }          
        //图形验证码
        if($this->cat["verify_code"]){
            if(!$data['verfy_code']){
                $this->error("请输入验证码");
            }
            if(!captcha_check($data['verfy_code'])){
                $this->error("验证码错误");
            };
        }
        //短信验证码
        if($this->cat["mobile_verify_code"]){
            if(!$data['mobile']){
                $this->error("请输入手机号码");
            }
            if(!$data['mobile_verify_code']){
                $this->error("请输入短信验证码");
            }            
            //验证
            if(!$this->mobile->check($data['mobile'],$data['mobile_verify_code'])){
                $this->error($this->mobile->error);
            }            
        }        
        //是否只针对指定用户
        if($this->cat["member_group"]){
            $group_id=Session::get("group_id");
            if(!strstr($this->cat["member_group"],",".$group_id.",")){
                $this->error("只针对指定用户开放，您无权操作");
            }
        }
    }
    //收集数据
    private function dataCreate($data){
        $return=[];
        //录入项
        $is_enter=$this->cat["is_enter"];
        $is_enter_arr=explode(",",trim($is_enter,","));
        //
        $where=[];
        $where[]=["field","in",$is_enter_arr];
        $fieldarr=$this->FieldModel->where($where)->select();
        foreach($fieldarr as $v){
            //复选框 多选下拉
            if($v['formtype']=="checkbox"||$v['formtype']=="selects"){
                //为数据导入的时候，表格里填写的是:上网|听音乐|打游戏 只要两边增加|即可
                if($type=="import_add"||$type=="import_update"){
                    if($data[$v['field']]){
                        $data[$v['field']]="|".$data[$v['field']]."|";
                    }
                }else{
                    $data[$v['field']]=implode("|",$data[$v['field']]);
                    if($data[$v['field']]){
                        $data[$v['field']]="|".$data[$v['field']]."|";
                    }
                }                
            } 
            //多值字段
            if($v['formtype']=="morevalue"){
                $morevalue_str="";
                $fieldLen=$data[$v['field']."_morevalue_len"];//获取一共有多少列字段
                $fieldValArr=array();
                foreach($fieldLen as $k1=>$v1){
                    $fieldValArr[$k1]=$data[$v['field']."_".$k1];
                }
                //根据第一列字段，提取有多个行数据,并循环
                foreach($fieldValArr[0] as $k2=>$v2){
                    //单个信息
                    $row_str="";
                    foreach($fieldValArr as $k3=>$fieldVal){
                        if($k3>0){
                            $row_str.="{{FieldSplit}}".$fieldVal[$k2];
                        }else{
                            $row_str=$fieldVal[$k2];
                        }
                    }
                    //多行信息拼接
                    if($morevalue_str){
                        $morevalue_str.="{{RsSplit}}".$row_str;
                    }else{
                        $morevalue_str=$row_str;
                    }
                }
                $data[$v['field']]=$morevalue_str;
            }             
            //日期
            if($v['formtype']=="date"){
               $data[$v['field']]=$data[$v['field']]?strtotime($data[$v['field']]):"";
            }       
            //判断是否为 int smallint tinyint bigint
            if(in_array($v['fieldtype'],array("tinyint","smallint","int","bigint"))){
               $data[$v['field']]=abs($data[$v['field']]);//禁止出现负数 
            }    
            //保息信息处理函数
            if($v['savefun']){
                $savefunArr=explode("###",$v['savefun']);
                $funVal=array();
                if($savefunArr[1]){
                    $funParmas=explode(",",$savefunArr[1]);
                    $funVal=array_merge(array($data[$v['field']]),$funParmas);
                }else{
                    $funVal=array($data[$v['field']]);
                }    
                $data[$v['field']]=call_user_func_array($savefunArr[0],$funVal);
            }            
        }
        $data['addtime']=time();
        $data['member_id']=$this->member_id;
        $data['ip']=  get_client_ip();     
        return $data;
    }   
}
